package com.shiro.demo.shiro;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author liup
 * @since 2020/10/20
 */
@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        //设置拦截
        Map<String,String> filters = new HashMap<>();
        //授权
        filters.put("/user/add","perms[user:add]");
        filters.put("/user/update","perms[user:update]");
        //无须认证即可访问
        filters.put("/index","anon");
        //必须认证才可以访问
        filters.put("/user/*","authc");

        //设置过滤器
        bean.setFilterChainDefinitionMap(filters);
        bean.setSuccessUrl("/index");
        bean.setUnauthorizedUrl("/login");
        bean.setLoginUrl("/login");
        bean.setUnauthorizedUrl("/nauth");
        return bean;
    }

    @Bean(name="securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("myRealm") MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        return securityManager;
    }
    @Bean
    public MyRealm myRealm(){
        return  new MyRealm();
    }

    //整合 shiro与thymeleaf
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
